package com.example.boot.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.boot.mapper.UserRoleMapper;
import com.example.boot.pojo.dto.Meta;
import com.example.boot.pojo.entity.Menu;
import com.example.boot.pojo.entity.User;
import com.example.boot.pojo.entity.UserRole;
import com.example.boot.pojo.result.Result;
import com.example.boot.pojo.vo.MenuChildVo;
import com.example.boot.pojo.vo.MenuVo;
import com.example.boot.pojo.vo.UserInfoVo;
import com.example.boot.service.MenuService;
import com.example.boot.service.UserService;
import com.example.boot.utils.GetCurrentUserInfo;
import com.example.boot.utils.RedisService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: mhpy
 * @date 2022/8/6 22:06
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Resource
    private GetCurrentUserInfo getCurrentUserInfo;
    @Resource
    private UserService userService;
    @Resource
    private RedisService redisService;
    @Resource
    private MenuService menuService;
    @Resource
    private UserRoleMapper userRoleMapper;



    @GetMapping("/getPage/{current}/{size}")
    public Result getAllUser(@PathVariable("current") Integer current, @PathVariable("size") Integer size){
        Page<User> userPage = userService.getAllUser(current,size);
        return Result.success().data("item",userPage);
    }

    @PreAuthorize("hasAnyAuthority('system:user:edit','system:user:add')")
    @PostMapping("/saveOrUpdate")
    public Result addOrUpdateUser(@RequestBody User user){
        userService.saveOrUpdate(user);
        return Result.success();
    }

    @PreAuthorize("hasAnyAuthority('system:user:delete')")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        userService.removeById(id);
//        用户删除需删除对应的用户角色的数据
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId,id));
        return Result.success();
    }

    @PreAuthorize("hasAuthority('system:user:assignment')")
    @PostMapping("/assignmentRole/{userId}/{roleId}")
    public Result assignmentRole(@PathVariable("userId") Integer userId,@PathVariable("roleId") Integer roleId){
        userService.assignmentRole(userId,roleId);
        return Result.success();
    }

    @GetMapping("currentUserRole/{userId}")
    public Result currentUserRole(@PathVariable("userId") Integer userId){
        String[] currentUserRoles = userService.getCurrentUserRoles(userId);
        return Result.success().data("item",currentUserRoles);
    }

    @GetMapping("/userInfo")
    public Result getUserInfo() {
//        当前用户信息
        User user = userService.getById(getCurrentUserInfo.getId());
//        当前用户菜单
        List<Menu> userMenu = menuService.getUserMenuList(getCurrentUserInfo.getId());
//        返回的列表视图  多类型 用object
//        List menuList = new ArrayList<>();
//        父菜单视图列表
        List<MenuVo> menuVo = new ArrayList<>();
//        顶级菜单无child 的 视图列表
//        List<MenuChildVo> noChild = new ArrayList<>();
//        菜单对应的角色
        String[] roles = userService.getCurrentUserRoles(getCurrentUserInfo.getId());
        for (Menu menu : userMenu) {
//            设置父菜单meta
            menu.setMeta(new Meta(menu.getName(),menu.getIcon(),roles));
//            菜单对象转化为菜单视图对象
            MenuVo menuVo1 = new MenuVo(menu.getPath(), menu.getName(), menu.getComponent(), menu.getRedirect(), menu.getMeta(), null);
//          //                顶级菜单无子菜单则 去掉children
//            MenuChildVo noChildren = new MenuChildVo();
//            判断有无子菜单
            if (menu.getChildren()!=null){
//                子菜单列表视图
                List<MenuChildVo> menuVoChild = new ArrayList<>();
                for (Menu child : menu.getChildren()) {
//                    判断是否为菜单
                    if (child.getType()==0){
                        child.setMeta(new Meta(child.getName(),child.getIcon(),roles));
                        menuVoChild.add(new MenuChildVo(child.getPath(), child.getName(), child.getComponent(), child.getRedirect(), child.getMeta()));
                    }
                }
                //            子菜单添加到父菜单
                menuVo1.setChildren(menuVoChild);
            }
//            转化好后的菜单添加到父菜单视图列表
            menuVo.add(menuVo1);
            }
//        当前用户的权限字段
        List<String>  permissions= menuService.selectPermissionValueByUserId(getCurrentUserInfo.getId());
//      生成用户信息
        UserInfoVo userInfoVo= new UserInfoVo(user.getName(),user.getAvatar(),user.getSex(),roles,permissions,menuVo);
        return Result.success().data("item",userInfoVo);
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        String token=request.getHeader("X-Token");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication!=null){
            //清除上下文信息
            new SecurityContextLogoutHandler().logout(request,response,authentication);
            redisService.delete("token_"+token);
        }
        return Result.success();
    }

}
